import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'

const routes = [
  {
    path: '/',
    component: () => import('../layouts/MainLayout.vue'),
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('../views/HomeView.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/DashboardView.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('../views/ProfileView.vue'),
        meta: { requiresAuth: true }
      }
    ]
  },
  {
    path: '/auth',
    component: () => import('../layouts/AuthLayout.vue'),
    children: [
      {
        path: 'login',
        name: 'Login',
        component: () => import('../views/LoginView.vue')
      },
      {
        path: 'register',
        name: 'Register',
        component: () => import('../views/RegisterView.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const token = localStorage.getItem('token')
  
  console.log('路由守卫 - 目标路由:', to.path)
  console.log('路由守卫 - localStorage中的token:', token)
  console.log('路由守卫 - store中的token:', userStore.token)
  console.log('路由守卫 - 当前登录状态:', userStore.isLoggedIn)
  
  // 如果localStorage中有token但store中没有，则从localStorage恢复
  if (token && !userStore.token) {
    console.log('从localStorage恢复token')
    userStore.token = token
  }
  
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    console.log('需要登录，重定向到登录页面')
    next({ name: 'Login' })
  } else {
    console.log('允许访问路由:', to.path)
    next()
  }
})

export default router